package com.rescue.service.impl;

import com.rescue.constant.MessageConstant;
import com.rescue.exception.BaseException;
import com.rescue.forum.entity.ForumBoard;
import com.rescue.forum.vo.BoardVO;
import com.rescue.forum.vo.UserAllBoardVO;
import com.rescue.mapper.BoardMapper;
import com.rescue.service.BoardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Service
public class BoardServiceImpl implements BoardService {
    @Autowired
    private BoardMapper boardMapper;

    /**
     * 获取所有父板块
     *
     * @return
     */
    public List<BoardVO> getPBoard() {
        return boardMapper.getBoardByP(0);
    }

    /**
     * 根据父板块获取子板块
     *
     * @param boardId
     * @return
     */
    public List<BoardVO> getBoardByP(Integer boardId) {
        return boardMapper.getBoardByP(boardId);
    }

    /**
     * 新增板块
     *
     * @param forumBoard
     */
    public void save(ForumBoard forumBoard) {
        boardMapper.insert(forumBoard);
    }

    /**
     * 删除板块
     * @param boardId
     */
    public void deleteByBoardId(Integer boardId) {
        //如果删除的板块有子板块
        //抛异常
        List<BoardVO> boardByP = boardMapper.getBoardByP(boardId);
        if (boardByP != null && boardByP.size() != 0) {
            throw new BaseException(MessageConstant.CONTAINING_SUB_PLATES);
        }
        boardMapper.deleteByBoardId(boardId);
    }

    /**
     * 修改板块
     * @param forumBoard
     */
    public void update(ForumBoard forumBoard) {
        boardMapper.update(forumBoard);
    }

    /**
     * 根据Id查询板块
     * @param id
     * @return
     */
    public ForumBoard getById(Integer id) {
        return boardMapper.getById(id);
    }

    /**
     * 客户端获取板块信息
     * @return
     */
    public List<UserAllBoardVO> userLoadBoard() {
        List<BoardVO> list = boardMapper.getBoardByP(0);
        List<UserAllBoardVO> listR = new ArrayList<>();

        list.forEach(boardVO -> {
            UserAllBoardVO userAllBoardVO = new UserAllBoardVO();
            BeanUtils.copyProperties(boardVO,userAllBoardVO);
            listR.add(userAllBoardVO);
        });
        listR.forEach(userAllBoardVO -> {
            List<BoardVO> boardByP = getBoardByP(userAllBoardVO.getBoardId());
            List<UserAllBoardVO> tempL = new ArrayList<>();
            boardByP.forEach(boardVO -> {
                UserAllBoardVO userAllBoardVO1 = new UserAllBoardVO();
                BeanUtils.copyProperties(boardVO, userAllBoardVO1);
                tempL.add(userAllBoardVO1);
            });
            userAllBoardVO.setChildren(tempL);
        });
        return listR;
    }
}
